import { useMemo } from "react";
import { m } from "framer-motion";
import { IEventItem } from "@/lib/types";
import EventItem from "./EventItem";
import { EventTypeColorMaps } from "@/lib/constants";

type CategoryViewProps = {
  events: IEventItem[];
};

export default function CategoryView(props: CategoryViewProps) {
  const { events } = props;

  const groupedEvents = useMemo(() => {
    const map = new Map<string, IEventItem[]>();
    events.forEach((event) => {
      if (!map.has(event.type)) {
        map.set(event.type, []);
      }
      map.get(event.type).push(event);
    });
    return Array.from(map.entries())
      .map(([type, list]) => ({ type, list }))
      .sort((a, b) => b.list.length - a.list.length);
  }, [events]);

  return (
    <div>
      {groupedEvents.map((group) => (
        <m.div key={group.type} layout>
          <m.h2
            initial={{ opacity: 0 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true, margin: "0px 0px -50px 0px" }}
            className="mb-2 mt-6 flex items-center"
          >
            <span
              className="mr-4 inline-block size-5 rounded-full border-2 border-white"
              style={{
                backgroundColor:
                  EventTypeColorMaps[group.type] || EventTypeColorMaps["其他"],
              }}
            />
            {group.type}
          </m.h2>
          <div className="grid grid-flow-row-dense grid-cols-2 gap-x-4">
            {group.list.map((event) => (
              <div key={event.id} id={`event-${event.id}`} className="py-2">
                <EventItem key={event.id} event={event} />
              </div>
            ))}
          </div>
        </m.div>
      ))}
    </div>
  );
}
